package com.wjl.springcloudalibaba.sentinel.gatewaysentinel.controller;

import com.wjl.springcloudalibaba.sentinel.gatewaysentinel.client.feign.EchoService;
import com.wjl.springcloudalibaba.sentinel.gatewaysentinel.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author wjl
 */
@RestController
public class TestController {

    @Autowired
    HelloService helloService;

    @Autowired
    EchoService echoService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping(value = "/hello")
    public String hello() {
        return helloService.hello();
    }

    @GetMapping(value = "/echoByFeign/{name}")
    public String echoByFeign(@PathVariable(value = "name") String name) {
        return "Feign: " + echoService.echo(name);
    }

    @GetMapping(value = "/echoByRestTemplate/{name}")
    public String echoByRestTemplate(@PathVariable(value = "name") String name) {
        // 使用这种方式还不行，猜测集成ribbon后才行。TODO 待验证
//        return "RestTemplate: " + restTemplate.getForObject("http://nacos-provider/echoByRestTemplate/{?}",
        String provider = "nacos-provider";
        List<ServiceInstance> instances = discoveryClient.getInstances(provider);
        ServiceInstance serviceInstance = instances.stream().findAny().orElseThrow(() -> new IllegalArgumentException("服务" + provider + "找不到"));
        return "RestTemplate: " + restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
                        + "/echo/{name}",
                String.class,
                name);
    }
}